import { Message } from 'element-ui'

export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
}

/**
 * 组装树
 * @param data
 * @param attributes
 * @returns {Array}
 */
export function toTreeData (data, attributes) {
  let resData = Object.assign([], data)
  let tree = []
  for (let i = 0; i < resData.length; i++) {
    if ((resData[i][attributes.parentId] === null || resData[i][attributes.parentId] === undefined || resData[i][attributes.parentId] === '') || resData[i][attributes.parentId] === resData[i][attributes.id]) {
      let obj = resData[i]
      obj['parentAccessCode'] = ''
      delete obj['children']
      tree.push(obj)
      resData.splice(i, 1)
      i--
    }
  }
  run(tree)
  function run (chiArr) {
    if (chiArr !== undefined && resData.length !== 0) {
      for (let i = 0; i < chiArr.length; i++) {
        delete chiArr[i]['children']
        let children = []
        for (let j = 0; j < resData.length; j++) {
          if (chiArr[i][attributes.id] === resData[j][attributes.parentId]) {
            let obj = resData[j]
            obj['parentAccessCode'] = chiArr[i]['accessCode']
            delete obj['children']
            children.push(obj)
            resData.splice(j, 1)
            j--
          }
        }
        if (children.length > 0) {
          chiArr[i].children = children
        }
        run(chiArr[i].children)
      }
    }
  }
  return tree
}

/**
 * 提示消息
 * @param text
 * @param type
 */
export function message (text, type) {
  Message({
    message: text,
    type: type,
    duration: 2 * 1000
  })
}

/**
 * 导出excel
 * @param table
 * @param sheetName
 * @param dataList
 * @param callback
 */
export function exportTableDownload (table, filename, sheetName, dataList, callback) {
  let [labels, props] = [[], []]
  for (let i of table.columns) {
    if (i.type !== 'index' && i.type !== 'selection' && i.property !== undefined) {
      labels.push(i.label)
      props.push(i.property)
    }
  }
  import('@/components/plugins/vendor/Export2Excel').then(excel => {
    const tHeader = labels
    const filterVal = props
    for (let i of dataList) {
      if (i.updatedTimestamp !== undefined && i.updatedTimestamp !== null) {
        i.updatedTimestamp = parseTime(Date.parse(i.updatedTimestamp))
      }
    }
    const data = dataList.map(v => filterVal.map(j => {
      let props_ = j.split('.'); let value = ''
      if (props_.length > 1) {
        let obj = null
        props_.forEach(function (op, i) {
          if (i === 0) {
            obj = v[op]
          } else {
            obj = obj[op]
          }
        })
        value = obj
      } else {
        value = v[j]
      }
      if (value === true) {
        return '是'
      } else if (value === false) {
        return '否'
      } else {
        return value
      }
    }))
    excel.export_json_to_excel({
      filename: filename || table.$attrs.label,
      sheetName: sheetName,
      header: tHeader,
      data
    })
    if (callback) {
      callback()
    }
  }
  )
}
// 导出一个Excel多个sheet
export function json2excel (tableJson, filenames, autowidth, bookTypes, callback) {
  import('@/components/plugins/vendor/Export2Excel').then(excel => {
    let [tHeader, dataArr, sheetnames] = [[], [], []]
    for (var i in tableJson) {
      tHeader.push(tableJson[i].tHeader)
      dataArr.push(formatJson(tableJson[i].filterVal, tableJson[i].tableDatas))
      sheetnames.push(tableJson[i].sheetName)
    }
    excel.export_json_to_excel_by_sheets({
      header: tHeader,
      data: dataArr,
      sheetname: sheetnames,
      filename: filenames,
      autoWidth: autowidth,
      bookType: bookTypes
    })
    if (callback) {
      callback()
    }
  })
}

function formatJson (filterVal, jsonData) {
  return jsonData.map(v =>
    filterVal.map(j => {
      if (j === 'timestamp') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
    })
  )
}

export function pagingData (data, pageNum = 1, pageSize = 10) {
  return data.slice((pageNum - 1) * pageSize, pageSize * pageNum)
}

// yyyy-MM-dd HH:mm:ss
export function dateFormat (value, fmt) {
  if (!value) {
    return
  }
  let date = new Date(value)
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

/**
 * 区分浏览器
 */
export function isIE () {
  return !!window.ActiveXObject || 'ActiveXObject' in window;
}
